package com.spring.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spring.security.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Classname: MyUserDetailServiceImpl
 * @Description: 查询数据库获取登录人信息
 * @Date: 2021/12/27
 * @Author: HuWei
 */
@Service
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserEntity::getUsername,username);
        UserEntity one = userService.getOne(queryWrapper);
        if(one == null){
            throw new UsernameNotFoundException("没有这个用户");
        }
        // 模拟获取权限信息,如果使用hasRole方法或者hasAnyRole方法,需要加上前缀ROLE_
        List<GrantedAuthority> roleList = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_sale");
        // 返回值是Security的User对象,里面有登录名,加密的密码,角色权限
        return new User(one.getUsername(), new BCryptPasswordEncoder().encode(one.getPassword()),roleList);
    }
}